package com.zff.rental.config;

import com.zff.rental.common.BusinessException;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * Minio配置
 *
 * @author HCY
 */
@Configuration
public class MinioConfig {
    @Value("${minio.host}")
    private String host;
    @Value("${minio.port}")
    private int port;
    @Value("${minio.access-key}")
    private String accessKeyId;
    @Value("${minio.secret-key}")
    private String accessKeySecret;
    @Value("${minio.bucket-name}")
    private String bucketName;

    /**
     * S3客户端对象
     */
    private volatile MinioClient minioClient;

    public MinioClient getMinioClient() {
        if (minioClient == null) {
            synchronized (MinioConfig.class) {
                if (minioClient == null) {
                    try {
                        minioClient = initMinioClient();
                    } catch (Exception e) {
                        throw new BusinessException(e.getMessage());
                    }
                }
            }
        }
        return minioClient;
    }

    private MinioClient initMinioClient() throws ServerException, InsufficientDataException,
            ErrorResponseException, IOException, NoSuchAlgorithmException,
            InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {

        MinioClient minioClient = MinioClient.builder().
                endpoint(host, port, false).
                credentials(accessKeyId, accessKeySecret)
                .build();

        if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        }

        return minioClient;
    }

    public String getDefaultBucketName() {
        return bucketName;
    }
}
